from ckeditor.fields import RichTextField
from django.db import models
from django.db.models import Sum
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _

from jiaozi.utils import hget_data, hset_data, model_data_from_cache, int_value


class ProductStyle(models.Model):
    name_cn = models.CharField(verbose_name=_('风格中文名'), max_length=255, unique=True)
    name_en = models.CharField(verbose_name=_('风格英文名'), max_length=255, null=True, blank=True)
    desc_cn = RichTextField(verbose_name=_('中文描述'), max_length=2000, null=True, blank=True)
    desc_en = RichTextField(verbose_name=_('英文描述'), max_length=2000, null=True, blank=True)
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['id']
        verbose_name = _('产品风格')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{0}".format(self.name_cn)


@receiver(post_save, sender=ProductStyle)
def post_save_product_style(sender, instance, **kwargs):
    model_data_from_cache(sender, instance.pk, force_update=True)


class ProductCategory(models.Model):
    name_cn = models.CharField(verbose_name=_('归类中文名'), max_length=255, unique=True)
    name_en = models.CharField(verbose_name=_('归类英文名'), max_length=255, null=True, blank=True)
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['id']
        verbose_name = _('产品归类')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{0}".format(self.name_cn)


class ProductInfo(models.Model):
    name_cn = models.CharField(verbose_name=_('中文名称'), max_length=255, null=True)
    name_en = models.CharField(verbose_name=_('英文名称'), max_length=255, null=True, blank=True)
    is_beer = models.BooleanField(verbose_name=_('是酒类'), default=True)
    # 酒类产品专属的字段
    abv = models.DecimalField(verbose_name=_('酒精度'), null=True, blank=True, max_digits=4, decimal_places=2)
    plato = models.DecimalField(verbose_name=_('糖度'), null=True, blank=True, max_digits=4, decimal_places=2)
    ibu = models.DecimalField(verbose_name='IBU', null=True, blank=True, max_digits=4, decimal_places=2)
    product_style = models.ForeignKey(
        ProductStyle,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name=_('产品风格')
    )
    bottle_size = models.DecimalField(verbose_name=_('容量ml'), null=True, blank=True, max_digits=6, decimal_places=2)
    # 产品图片，必填字段
    main_image = models.ImageField(verbose_name=_('主图片'), upload_to='media/product/%Y%m/', null=True, blank=True)
    barcode = models.CharField(verbose_name=_('条码'), max_length=100, null=True, blank=True)
    short_desc_cn = models.CharField(verbose_name=_('中文简介'), max_length=255, blank=True, default='')
    short_desc_en = models.CharField(verbose_name=_('英文简介'), max_length=255, blank=True, default='')
    desc_cn = RichTextField(verbose_name=_('中文描述'), max_length=2000, null=True, blank=True)
    desc_en = RichTextField(verbose_name=_('英文描述'), max_length=2000, null=True, blank=True)

    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['-id']
        verbose_name = _('1.产品信息')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{0}".format(self.name_cn)


@receiver(post_save, sender=ProductInfo)
def post_save_product_info(sender, instance, **kwargs):
    model_data_from_cache(sender, instance.pk, force_update=True)


class ProductBatch(models.Model):
    product_info = models.ForeignKey(
        ProductInfo,
        on_delete=models.CASCADE,
        verbose_name=_('产品')
    )
    production_date = models.DateField(verbose_name=_('生产日期'), null=True, blank=True)
    expiration_date = models.DateField(verbose_name=_('过期日期'), null=True, blank=True)
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['-id']
        verbose_name = _('2.产品批次')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{} {}".format(self.production_date, self.product_info)


@receiver(post_save, sender=ProductBatch)
def post_save_product_batch(sender, instance, **kwargs):
    model_data_from_cache(sender, instance.pk, force_update=True)


class ProductIn(models.Model):
    product_batch = models.ForeignKey(
        ProductBatch,
        on_delete=models.CASCADE,
        verbose_name=_('产品批次')
    )
    amount = models.IntegerField(verbose_name=_('数量'), null=True, blank=True)
    date_in = models.DateTimeField(verbose_name=_('入库时间'), null=True, blank=True)
    notes = models.TextField(verbose_name=_('备注'), max_length=2000, null=True, blank=True)
    created_by = models.ForeignKey(
        'app.WxUser',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name=_('创建人'),
        related_name='product_in_created_by',
    )
    updated_by = models.ForeignKey(
        'app.WxUser',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name=_('更新人'),
        related_name='product_in_updated_by',
    )
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['-id']
        verbose_name = _('3.产品入库')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{0}".format(self.product_batch.product_info.name_cn)


class ProductSales(models.Model):
    product_batch = models.ForeignKey(
        ProductBatch,
        on_delete=models.CASCADE,
        verbose_name=_('产品批次')
    )
    price_show = models.DecimalField(verbose_name=_('展示价格'), null=True, max_digits=10, decimal_places=2)
    order_index = models.SmallIntegerField(verbose_name=_('排序编号'), default=1)
    amount_initial = models.IntegerField(verbose_name=_('发售数量'))
    current_sales = models.IntegerField(verbose_name=_('已售数量'), default=0)
    amount_per_user_max = models.IntegerField(verbose_name=_('每个用户最多购买数'), default=1)
    is_vip_only = models.BooleanField(verbose_name=_('会员专享'), default=False)
    vip_level = models.ManyToManyField(
        'vip.VipLevel',
        blank=True,
        verbose_name=_("用户等级")
    )
    product_category = models.ManyToManyField(
        ProductCategory,
        blank=True,
        verbose_name=_('产品归类')
    )
    main_image = models.ImageField(verbose_name=_('主图片'), upload_to='media/product/%Y%m/', null=True, blank=True)
    is_show = models.BooleanField(verbose_name=_('上架'), default=True, help_text=_('如果去除此勾选，为强制下架此商品'))
    show_start = models.DateTimeField(verbose_name=_('上架时间'), null=True, help_text=_('页面上开始显示此产品的时间'))
    sales_start = models.DateTimeField(verbose_name=_('发售开始时间'), null=True, help_text=_('用户可以购买此商品的时间'))
    sales_end = models.DateTimeField(verbose_name=_('发售结束时间'), null=True)
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    def amount_left_property(self):
        # 获取已发售数量
        res = int_value(self.amount_initial) - int_value(self.current_sales)
        return res

    amount_left_property.short_description = '剩余库存'
    amount_left = property(amount_left_property)

    def get_image(self):
        if not self.main_image:
            self.main_image = self.product_batch.product_info.main_image

    class Meta:
        ordering = ['-id']
        verbose_name = _('4.在售商品')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{}. {} {}".format(self.pk, self.product_batch_id, self.price_show)


@receiver(pre_save, sender=ProductSales)
def pre_save_product_sales(sender, instance, **kwargs):
    instance.get_image()


@receiver(post_save, sender=ProductSales)
def post_save_product_sales(sender, instance, **kwargs):
    model_data_from_cache(sender, instance.pk, force_update=True)


class Banner(models.Model):
    product_sales = models.ForeignKey(
        ProductSales,
        on_delete=models.PROTECT,
        null=True,
        blank=True,
        verbose_name=_('在售商品')
    )
    name_cn = models.CharField(verbose_name=_('中文名称'), max_length=255, null=True, blank=True)
    name_en = models.CharField(verbose_name=_('英文名称'), max_length=255, null=True, blank=True)
    order_index = models.SmallIntegerField(verbose_name=_('排序编号'), default=1)
    banner_image = models.ImageField(verbose_name=_('广告照片'), upload_to='media/product/%Y%m/', null=True)
    jump_url = models.CharField(verbose_name=_('跳转地址'), max_length=255, default='', blank=True)
    show_start = models.DateTimeField(verbose_name=_('开始展示'), null=True)
    show_end = models.DateTimeField(verbose_name=_('结束展示'), null=True, blank=True)
    is_show = models.BooleanField(verbose_name=_('是否展示'), default=True)
    datetime_created = models.DateTimeField(verbose_name=_('创建时间'), auto_now_add=True)
    datetime_updated = models.DateTimeField(verbose_name=_('更新时间'), auto_now=True)

    objects = models.Manager()

    class Meta:
        ordering = ['-id']
        verbose_name = _('5.置顶广告')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{0}".format(self.name_cn)


class HotSearch(models.Model):
    key_word = models.CharField(verbose_name=_('关键词'), max_length=255, default='')
    count = models.BigIntegerField(verbose_name=_('次数'), default=1)
    is_show = models.BooleanField(verbose_name=_('是否展示'), default=True)

    objects = models.Manager()

    class Meta:
        ordering = ['-count']
        verbose_name = _('热门搜索')
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{} {}".format(self.key_word, self.count)
